package ld.oauth.blog.service.article.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ld.oauth.blog.mapper.article.ArticleCategoryMapper;
import ld.oauth.blog.mapper.article.CategoryMapper;
import ld.oauth.blog.model.po.article.ArticleCategory;
import ld.oauth.blog.model.po.article.Category;
import ld.oauth.blog.model.vo.CategoryLabelVo;
import ld.oauth.blog.model.vo.LabelVo;
import ld.oauth.blog.service.article.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ld
 * @since 2022-09-24
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ArticleCategoryMapper articleCategoryMapper;

    @Override
    public List<CategoryLabelVo> categoryLabelVoList() {
        List<Category> categoryList = this.getBaseMapper().selectList(new QueryWrapper<>());
        List<CategoryLabelVo> categoryLabelVoList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(categoryList)){
            categoryList.stream().forEach(category->{
                CategoryLabelVo categoryLabelVo = new CategoryLabelVo();
                BeanUtils.copyProperties(category,categoryLabelVo);
                List<LabelVo> labelVoList = categoryMapper.selectLabelVoListByCategoryId(category.getId());
                categoryLabelVo.setLabelList(labelVoList);
                categoryLabelVoList.add(categoryLabelVo);
            });
        }
        return categoryLabelVoList;
    }

    @Override
    public List<Category> getList() {
        List<Category> list = this.list();
        List<Integer> categoryIdList = list.stream().map(Category::getId).distinct().collect(Collectors.toList());
        List<ArticleCategory> articleCategorytList = articleCategoryMapper.getCArticleCategorytByCategoryIdList(categoryIdList);
        Map<Integer, List<ArticleCategory>> map = articleCategorytList.stream().collect(Collectors.groupingBy(ArticleCategory::getCategoryId));
        list.stream().forEach(category -> {
            Integer categoryId = category.getId();
            List<ArticleCategory> articleCategoryList = map.get(categoryId);
            if(CollectionUtils.isEmpty(articleCategoryList)){
                return;
            }
            category.setArticleCount(articleCategoryList.size());
        });
        return list;
    }
}
